package activity.store;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.View;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.itboye.hutoubenjg.R;

import java.util.ArrayList;
import java.util.List;
import java.util.Observable;
import java.util.Observer;

import adapter.ShopCartAdapter;
import base.BaseActivity;
import bean.GouWuCheBean;
import presenter.OrderPresenter;
import util.utls.ByAlert;
import util.utls.Const;
import util.utls.IsUtilUid;
import util.utls.MyGongJv;
import util.utls.SPUtils;
import util.volley.ResultEntity;


/**
 * 购物车
 */
public class ShopCartActivity extends BaseActivity implements Observer, ShopCartAdapter.CheckBoxInterface, ShopCartAdapter.ModifyCountInterface {
    ImageView back;
    private ListView exListView;
    private TextView tv_total_price;
    private TextView tv_delete;
    private TextView tv_go_to_pay;
    public static ShopCartActivity context;
    CheckBox all_chekbox;
    ShopCartAdapter adapter;
    private List<GouWuCheBean> beanList;
    OrderPresenter presenter;
    String uid;
    private double totalPrice = 0.00;// 购买的商品总价
    private int totalCount = 0;// 购买的商品总数量
    LinearLayout linearOrder;
    private ArrayList<GouWuCheBean> list = new ArrayList<GouWuCheBean>();
    LinearLayout li_bottom;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_shop_cart);
        uid = (String) SPUtils.get(this, null, Const.ID, "");
        presenter = new OrderPresenter(this);
        showProgressDialog("获取商品,请稍后", true);
        presenter.gouWuChe(uid);
        adapter = new ShopCartAdapter(beanList, this);
        context = this;
        // 购物结束的广播
        IntentFilter filter1 = new IntentFilter(GoPayActivity.GOUWUINEXIT);
        registerReceiver(shuaxin, filter1);

        // 购物结束的刷新
        IntentFilter filter = new IntentFilter(CommitOrderActivity.GOUWUSHUXIN);
        registerReceiver(shuaxin, filter);

        //重新登录的时候推出该页面
        IntentFilter intentFilter = new IntentFilter("chaingLogin");
        registerReceiver(endtReceiver, intentFilter);

    }

    BroadcastReceiver endtReceiver = new BroadcastReceiver() {
        public void onReceive(Context context, Intent intent) {
            finish();
        }
    };
    BroadcastReceiver shuaxin = new BroadcastReceiver() {
        public void onReceive(Context context, Intent intent) {
            presenter.gouWuChe(uid);
            tv_total_price.setText("¥" + 0.00);
            tv_go_to_pay.setText("去支付(" + 0 + ")");
        }
    };

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(shuaxin);
        unregisterReceiver(endtReceiver);
    }

    @Override
    protected void onInit() {

    }

    @Override
    protected void onReadIntent(Bundle bundle) {

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.back:
                finish();
                break;
            case R.id.all_chekbox://全选
                doCheckAll();
                break;
            case R.id.tv_go_to_pay://购物车去支付
//                ArrayList<GouWuCheBean> tempList = new ArrayList<>();
//                StringBuffer string = new StringBuffer();
//                if (tempList != null) {
//                    if (tempList.size() > 0) {
//                        Intent intent = new Intent(this, CommitOrderActivity.class);
//                        intent.putExtra("list", tempList);
//                        startActivity(intent);
//                    } else {
//                        ByAlert.alert("请先选择要结算的商品!");
//                    }
//                }
                if (totalCount == 0) {
                    ByAlert.alert("请先选择要结算的商品!");
                    return;
                }
                Intent intent = new Intent(this, CommitOrderActivity.class);
                Bundle bundle = new Bundle();
                bundle.putSerializable("list", list);
                bundle.putSerializable("money", MyGongJv.zhuanhua(totalPrice));
                intent.putExtras(bundle);
                startActivity(intent);

                break;
        }
    }


    @Override
    public void update(Observable observable, Object data) {
        ResultEntity entity = handlerError(data);
        if (entity != null) {
            IsUtilUid.tianjia(entity);
            if (entity.getEventType() == OrderPresenter.addAll_success) {
                beanList = (List<GouWuCheBean>) entity.getData();
                if (beanList.size() > 0) {
                    setVisible();
                } else {
                    setGone();
                }
            }
        }
        try {
            closeProgressDialog();
        } catch (Exception e) {
        }
    }

    public void setVisible() {
        adapter = new ShopCartAdapter(beanList, this);
        adapter.setCheckInterface(this);//实现复选框接口
        adapter.setModifyCountInterface(this);//数量增减接口
        exListView.setAdapter(adapter);
        exListView.setVisibility(View.VISIBLE);
        linearOrder.setVisibility(View.GONE);
        li_bottom.setVisibility(View.VISIBLE);
    }

    public void setGone() {
        exListView.setVisibility(View.GONE);
        linearOrder.setVisibility(View.VISIBLE);
        li_bottom.setVisibility(View.GONE);
    }

    /**
     * 这个方法是为了删除商品之后判断剩余的商品是否全选
     */
    public void quanxuan() {
        if (isAllCheck()) {
            all_chekbox.setChecked(true);
        } else {
            all_chekbox.setChecked(false);
        }
    }

    /**
     * 统计操作<br>
     * 1.先清空全局计数器<br>
     * 2.遍历所有子元素，只要是被选中状态的，就进行相关的计算操作<br>
     * 3.给底部的textView进行数据填充
     */
    public void calculate() {
        totalCount = 0;
        totalPrice = 0.00;
        list = new ArrayList<GouWuCheBean>();
        for (int i = 0; i < beanList.size(); i++) {
            GouWuCheBean bean = beanList.get(i);
            if (bean.getItem_status().equals("1")) {
                if (bean.isSelected()) {
                    totalCount++;
                    totalPrice += (Double.parseDouble(bean.getPrice()) / 100) * bean.getCount();
                    list.add(bean);
                }
            }
        }
        tv_total_price.setText("¥" + MyGongJv.zhuanhua(totalPrice));
        tv_go_to_pay.setText("去支付(" + totalCount + ")");
    }

    /**
     * 全选与反选
     */
    private void doCheckAll() {
        for (int i = 0; i < beanList.size(); i++) {
            if (beanList.get(i).getItem_status().equals("1")) {
                beanList.get(i).setSelected(all_chekbox.isChecked());
            }
        }
        calculate();
        adapter.notifyDataSetChanged();
    }

    /**
     * 判断选项是不是都选了
     *
     * @return
     */
    public boolean isAllCheck() {
        for (int i = 0; i < beanList.size(); i++) {
            if (beanList.get(i).getItem_status().equals("1")) {
                if (!beanList.get(i).isSelected()) {
                    return false;
                }
            }
        }
        return true;
//        for (GouWuCheBean group : beanList) {
//            if (!group.isSelected())
//                return false;
//        }
//        return true;
    }

    /**
     * 选框状态改变时触发的事件
     *
     * @param position  子元素位置
     * @param isChecked 子元素选中与否
     */
    @Override
    public void checkChild(int position, boolean isChecked) {
        beanList.get(position).setSelected(isChecked);
        if (isAllCheck()) {//如果项目都被选中，则全选按扭设置成选中状态
            all_chekbox.setChecked(true);
        } else {
            all_chekbox.setChecked(false);
        }
        calculate();
    }
    /**
     * 修改
     */
    @Override
    public void xiugaiChild(int position, boolean isChecked) {
        beanList.get(position).setXiugai(isChecked);
        adapter.notifyDataSetChanged();
    }

    @Override
    public void doIncrease(int position, View showCountView, boolean isChecked, String id, String num) {
//        GouWuCheBean bean = (GouWuCheBean) adapter.getItem(position);
//        int currentCount = bean.getCount();
        int kc = Integer.parseInt(beanList.get(position).getQuantity());
        int number = (int)Double.parseDouble(num);
        if (number >= kc) {
            ByAlert.alert("库存"+kc);
            return;
        }
        number += 1;
        beanList.get(position).setCount(number);
        adapter.notifyDataSetChanged();
    }

    @Override
    public void doDecrease(int position, View showCountView, boolean isChecked, String id, String num) {
//        GouWuCheBean bean = (GouWuCheBean) adapter.getItem(position);
//        int currentCount = bean.getCount();
//        if (currentCount == 0) {
//            ByAlert.alert("已经为0");
//            return;
//        }
//        currentCount -= 1;
        int number = Integer.parseInt(num);
        if (number == 1) {
            ByAlert.alert("至少有一件商品");
            return;
        }
        number -= 1;
        beanList.get(position).setCount(number);
        adapter.notifyDataSetChanged();
    }

    @Override
    public void onBaoCun(int position, View showCountView, boolean isChecked, String id, String num) {
        int number = Integer.parseInt(num);

        beanList.get(position).setCounts(number);
        beanList.get(position).setCount(number);
        adapter.notifyDataSetChanged();
    }
}
